<?php

namespace JsonLowCode\Form\Fields;

use JsonLowCode\UI\Input;
use JsonLowCode\Form\Abstract\FieldAbstract;
use JsonLowCode\Form\Traits\HasClearable;
use JsonLowCode\Form\Traits\HasDisabled;
use JsonLowCode\Form\Traits\HasPlaceholder;
use JsonLowCode\Form\Traits\HasPrefix;
use JsonLowCode\Form\Traits\HasReadonly;
use JsonLowCode\Form\Traits\HasSize;
use JsonLowCode\Form\Traits\HasSuffix;

/**
 * @property Input $element
 */
class TextField extends FieldAbstract
{
    use HasDisabled, HasSize, HasPlaceholder, HasClearable, HasReadonly, HasPrefix, HasSuffix;

    protected string $type = "text";


    protected function booting(): void
    {
        $this->element = new Input($this->type);
        if (is_string($this->label)){
            $this->placeholder("请输入".$this->label);
        }else{
            $this->placeholder("请输入内容");
        }
        $this->setValue();
    }

    public function defaultValue(mixed $value = null): static
    {
        if (!is_array($value)){
            $value = strval($value);
        }
        return parent::defaultValue($value);
    }

    /**
     * @return $this
     */
    public function setValue(): static
    {
        $data = $this->form->getData();
        if ($data){
            $this->value = $data->value($this->field);
        }
        return $this;
    }

    protected function render(): void
    {
        if ($this->placeholder!=null){
            $this->element->placeholder($this->placeholder);
        }
    }
}
